<template>
<div class="product-container">
    <el-card class="product-card" shadow="never">
        <!-- 搜索区域 -->
        <div class="search-bar">
            <el-form :inline="true" :model="search" class="search-form">
                <el-form-item label="商品名称">
                    <el-input v-model="search.name" placeholder="请输入商品名称" clearable />
                </el-form-item>
                <el-form-item label="商品分类">
                    <el-select v-model="search.categoryId" placeholder="请选择分类" clearable style="width: 160px">
                        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="价格区间">
                    <el-input-number v-model="search.minPrice" :min="0" :precision="2" :step="10" placeholder="最低价"
                    style="width: 130px" />
                    <span class="price-separator">-</span>
                    <el-input-number v-model="search.maxPrice" :min="0" :precision="2" :step="10" placeholder="最高价"
                    style="width: 130px" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select style="width: 100px" v-model="search.status" placeholder="请选择状态" clearable>
                        <el-option label="上架" :value="1" />
                        <el-option label="下架" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="pageSearch()">
                        <el-icon>
                            <Search />
                        </el-icon>搜索
                    </el-button>
                    <el-button @click="search = getInitProductSearch()">
                        <el-icon>
                            <Refresh />
                        </el-icon>重置
                    </el-button>
                </el-form-item>
            </el-form>
            <div class="operation-bar">
                <el-button type="primary" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>新增商品
                </el-button>
            </div>
        </div>

        <!-- 商品表格 -->
         <el-table ref="productTableRef" 
           :data="products"
           border stripe 
           style="width: 100%" 
           height="calc(100vh - 280px)">
           <el-table-column type="index" label="序号" width="60" align="center" />
           <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip>
                <template #default="{ row }">
                    <div class="product-info">
                        <el-image :src="row.image" fit="cover" class="product-image" />
                        <div class="product-detail">
                            <div class="product-name">{{ row.name }}</div>
                            <div class="product-desc" :title="row.description">{{ row.description }}</div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="标签">
                <template #default="{ row }">
                    <div class="price-info">
                    <el-tag closable 
                        v-if="row.tags != undefined && row.tags.length > 0"
                        v-for="tag in row.tags.split(',')" :key="tag"
                        @close="handleDeleteTag(row, tag)">
                        {{ tag }}
                    </el-tag>
                    <el-button v-if="row.tags.split(',').length < 2"
                    class="button-new-tag" 
                    size="small" 
                    @click="openAddTag(row)">
                        + New Tag
                    </el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="categoryName" label="商品分类" width="120" align="center" />
            <el-table-column label="现价/原价" width="150" align="center" sortable prop="currentPrice">
                <template #default="{ row }">
                    <div class="price-info">
                        <span class="current-price">￥{{ row.currentPrice }}</span>
                        <span class="original-price">￥{{ row.originalPrice }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="monthlySales" label="月销量" width="100" align="center" sortable>
                <template #default="{ row }">
                    <span class="monthly-sales">{{ row.monthlySales }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100" align="center" sortable>
                <template #default="{ row }">
                    <el-tag :type="row.stock <= 10 ? 'danger' : row.stock <= 20 ? 'warning' : 'success'" effect="plain" size="small">
                        {{ row.stock }}
                    </el-tag>
                    <el-tooltip v-if="row.stock <= 10" effect="dark" content="库存不足，请及时补货" placement="top">
                        <el-icon class="warning-icon">
                            <Warning />
                        </el-icon>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="unit" label="商品单位" width="120" align="center"/>
            <el-table-column prop="createTime" label="上架日期" width="120" align="center" sortable/>
            <el-table-column prop="status" label="状态" width="100" align="center">
                <template #default="{ row }">
                    <el-switch 
                      v-model="row.status" 
                      :active-value="true" 
                      :inactive-value="false"
                      @change="handleStatusChange(row)" 
                      inline-prompt
                      :active-text="row.status ? '已上架' : ''" 
                      :inactive-text="row.status == false ? '已下架' : ''"
                      style="--el-switch-on-color: #13ce66" />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button-group class="operation-group">
                        <el-tooltip content="编辑" placement="top">
                            <el-button type="primary" link @click="handleEdit(row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button type="danger" link @click="handleDelete(row)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            </el-button>
                        </el-tooltip>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination 
                v-model:current-page="page.currentPage" 
                v-model:page-size="page.pageSize" 
                :page-sizes="[5, 10, 20]"
                :total="page.total" 
                layout="total, sizes, prev, pager, next, jumper" 
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </el-card>
</div>

<!-- 新增/编辑 商品对话框 -->    
<el-dialog 
  v-model="dialogVisible" 
  :title="isEdit ? '编辑商品' : '新增商品'" 
  width="600px" 
  :close-on-click-modal="false"
  @close="handleDialogClose">
    <el-form
      ref="formRef" 
      :model="form"
      :rules="productFormRules" 
      label-width="100px" 
      class="product-form"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
          <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入商品描述" />
      </el-form-item>
      <el-form-item label="商品价格">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="currentPrice">
              <el-input-number v-model="form.currentPrice" :precision="2" :step="0.1" :min="0" placeholder="现价"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="originalPrice">
              <el-input-number v-model="form.originalPrice" :precision="2" :step="0.1" :min="0" placeholder="原价"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="商品库存" prop="stock">
        <el-input-number v-model="form.stock" :min="0" :step="1" placeholder="请输入库存数量" style="width: 200px" />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="form.unit" placeholder="请输入商品单位" style="width: 200px" />
      </el-form-item>
      <el-form-item label="商品图片" prop="image">
        <img v-if="isEdit && showImage" :src="backImage" width="150px" style="margin-right: 20px;"/>
        <el-upload 
            ref="upload"
            action="#" 
            list-type="picture-card" 
            :auto-upload="false" 
            :multiple="false" 
            :limit="1"
            :on-change="handleOnChange"
            :on-exceed="handleOnExceed">
          <el-icon>
            <Plus />
          </el-icon>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <span class="el-upload-list__item-actions">
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品状态">
        <el-switch 
            v-model="form.status" :active-value="true"
            :inactive-value="false" inline-prompt :active-text="'上架'"
            :inactive-text="'下架'" style="--el-switch-on-color: #13ce66" 
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit(formRef)">
          确定
        </el-button>
      </span>
    </template>
</el-dialog>

<!-- 添加商品标签窗口 -->
<el-dialog title="新增标签" v-model="showAddTag">
    <el-form 
        ref="formRef" 
        :model="tagsForm"
        label-width="100px" 
        class="product-form"
    >
        <el-form-item label="标签" prop="name">
            <el-input v-model="tagsForm.tags" placeholder="请输入标签" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showAddTag = false">取消</el-button>
                <el-button type="primary" @click="handleAddTags()">确定</el-button>
            </span>
        </template>
</el-dialog>
</template>

<script setup lang="ts">
import { Page } from '@/models/baseModel';
import { Category, CategoryApi } from '@/models/categoryModel';
import { getInitProductForm, getInitProductSearch, Product, ProductApi, ProductForm, productFormRules, ProductSearch } from '@/models/productModel';
import { ElMessage, ElMessageBox, FormInstance, UploadFile, UploadFiles, UploadUserFile } from 'element-plus';
import { onMounted, ref } from 'vue';

// 是否打开/关闭，新增/编辑商品 对话框
const dialogVisible = ref<boolean>(false)
// 编辑/新增
const isEdit = ref<boolean>(false)
// 分类数据列表
const categoryOptions = ref<Category[]>([])
// 是否显示图片（在编辑商品时，显示商品原图片）
const showImage = ref<boolean>(true)
const backImage = ref()
const disabled = ref(false)     // 是否显示删除图片按钮
const upload = ref()            // 上传图片组件
// 商品数据表单
const form = ref<ProductForm>(getInitProductForm())
const formRef = ref<FormInstance>()
// 搜索实体
const search = ref<ProductSearch>(getInitProductSearch())
// 商品数据列表
const products = ref<Product[]>([])
// 分页
const page = ref<Page>({currentPage: 1, pageSize: 5, total: 0})
// 商品标签数据
const showAddTag = ref(false)
const tagsForm = ref({tags: '', id: ''})

onMounted(() => {
    // 获取分类数据
    CategoryApi.getAll()
    .then(data => {categoryOptions.value = data})
    // 获取商品数据
    pageSearch()
})

// 打开新增
const handleAdd = () => {
    isEdit.value = false
    form.value = getInitProductForm()
    dialogVisible.value = true
}

// 关闭 新增/编辑商品 窗口时
const handleDialogClose = () => {
    upload.value!.clearFiles()
    showImage.value = false
}

// 打开编辑窗口
const handleEdit = (row: Product) => {
    isEdit.value = true
    form.value = {...row}
    dialogVisible.value = true
    showImage.value = true
    backImage.value = row.image
}

// 删除商品
const handleDelete = (row: Product) => {
    ElMessageBox.confirm('确定要删除该商品吗？', '警告')
    .then(() => {
        // 这里应该调用删除API
        ProductApi.deleteById(row.id)
        .then(() => {
            products.value = products.value.filter(item => item.id != row.id)
        })
    })
    .catch(() => {})
}

// 打开添加商品标签窗口
const openAddTag = (row: Product) => {
  showAddTag.value = true
  tagsForm.value.id = row.id
  tagsForm.value.tags = ''
}

// 新增商品标签
const handleAddTags = () => {
  ProductApi.addTags(tagsForm.value)
  .then(res => {
    const index = products.value.findIndex(p => p.id == res.id)
    products.value[index] = res
    showAddTag.value = false
  })
}

// 删除商品标签
const handleDeleteTag = (row: Product, tag: string) => {
  ProductApi.deleteTags(row.id, tag)
  .then(res => {
    const index = products.value.findIndex(p => p.id == res.id)
    products.value[index] = res
  })
}

// 提交表单
const handleSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                ProductApi.updateById(form.value, form.value.id)
                .then(res => {
                    const index = products.value.findIndex(p => p.id == res.id)
                    products.value[index] = res
                    // 关闭表单
                    dialogVisible.value = false
                })
            } 
            else if (!isEdit.value) {
                ProductApi.create(form.value)
                .then(res => {
                    // 重新加载列表
                    products.value.push(res)
                    // 关闭表单
                    dialogVisible.value = false
                })
            }
        }
    })
}

// 修改商品状态
const handleStatusChange = (row: Product) => {
  const form: ProductForm = {...row, image: undefined}
  ProductApi.updateById(form, row.id)
  .then(() => {})
}

// 分页获取数据
const pageSearch = (currentPage: undefined | number = undefined) => {
    if (currentPage) page.value.currentPage = currentPage
    ProductApi.pagingSearch(search.value, page.value)
    .then(resultPage => {
        page.value.currentPage = resultPage.currentPage
        page.value.pageSize = resultPage.pageSize
        page.value.total = resultPage.total
        products.value = resultPage.data
    })
}

// 每页大小改变时
const handleSizeChange = (val: number) => {
    page.value.pageSize = val
    pageSearch()
}

// 页码改变时
const handleCurrentChange = (val: number) => {
    page.value.currentPage = val
    pageSearch()
}

// 当选择了一个图片
const handleOnChange = (uploadfile: UploadFile, uploadFiles: UploadFiles) => {
    form.value.image = uploadfile.raw
    // 不是编辑状态，不显示商品原图
    if (isEdit) showImage.value = false
}

// 重复选择图片时
const handleOnExceed = (files: File[], uploadFiles: UploadUserFile[]) => {
  ElMessage.error("图片已经选择!")
}

// 删除选中图片
const handleRemove = (file: UploadFile) => {
  upload.value!.clearFiles()
  if (isEdit) {
    showImage.value = true
    form.value.image = backImage.value
  }
}
</script>

<style scoped>
.product-container {
  height: 100%;
}

.product-card {
  height: 100%;
  border-radius: 8px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

:deep(.el-card__body) {
  height: calc(100% - 40px);
  display: flex;
  flex-direction: column;
  padding: 16px;
}

:deep(.el-table) {
  flex: 1;
}

:deep(.el-table__row) {
  height: 60px;
}

:deep(.el-table__cell) {
  padding: 8px 0;
}

.product-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.product-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-size: 14px;
  color: #303133;
  line-height: 1.4;
}

.product-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.current-price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

.original-price {
  color: #909399;
  font-size: 14px;
  text-decoration: line-through;
}

.monthly-sales {
  color: #67c23a;
  font-weight: bold;
}

.listing-date {
  color: #606266;
  font-size: 13px;
}

.operation-group {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.operation-group .el-button {
  font-size: 16px;
  padding: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

:deep(.el-tag) {
  padding: 0 8px;
  min-width: 45px;
}

/* 表格滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  border-radius: 3px;
  background: #dcdfe6;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  border-radius: 3px;
  background: #f5f7fa;
}

.operation-bar {
  display: flex;
  gap: 16px;
}

.price-separator {
  margin: 0 8px;
  color: #909399;
}

.price-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.warning-icon {
  margin-left: 4px;
  color: var(--el-color-danger);
  font-size: 16px;
  vertical-align: -0.15em;
}

/* 新增商品表单样式 */
.product-form {
  padding: 20px;
}

.avatar-uploader {
  /* border: 1px dashed var(--el-border-color); */
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

/* 添加上传提示样式 */
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  padding-left: 10px;
}

/* 调整表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number.is-controls-right .el-input__wrapper) {
  padding-right: 40px;
}

/* 添加编辑表单特有样式 */
.edit-form {
  .el-input-number {
    width: 100%;
  }
}
</style>